<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Cache;
use think\Cookie;
use think\Session;
use app\common\controller\Base;

class Everyone extends Base {

    /**
     * @title 清除umeditor上传的文件没有在文章内容中被引用的
     */
    public function clear_umeditor() {


        // 查找所有ueditor/php/upload/image/所有文件
        $arr1 = [];

        // 文章
        $article_lists = db('article')->column('content');
        foreach ($article_lists as $key => $value) {
            // 正则匹配img
            preg_match_all('/<img src="(.*?)"/', $value, $matchs);

            if (isset($matchs[1])) {
                foreach ($matchs[1] as $value2) {
                    $arr1[] = $value2;
                }
            }
        }

        // 商品
        $goods_lists = db('goods')->column('content');
        foreach ($goods_lists as $key => $value) {
            // 正则匹配img
            preg_match_all('/<img src="(.*?)"/', $value, $matchs);

            if (isset($matchs[1])) {
                foreach ($matchs[1] as $value2) {
                    $arr1[] = $value2;
                }
            }
        }


        // 查找 所有article 和goods 表content字段是图片 路径
        $arr2 = [];
        $this->myscandir1(APP_DIR . DIRECTORY_SEPARATOR . 'ueditor', $arr2);



        echo '<form action="" method="get"><button type=submit name=delete value="ok">删除以下文件</button></form>';

        foreach ($arr2 as $value) {

            $value2 = str_replace(APP_DIR, '', $value);

            if (!in_array($value2, $arr1)) {
                echo $value2 . '<br>';

                if (request()->get('delete') == 'ok') {
                    @unlink($value);
                }
            }
        }
        
        
    }

    public function myscandir1($path, &$arr) {
        foreach (glob($path) as $file) {
            if (is_dir($file)) {
                $this->myscandir1($file . '/*', $arr);
            } else {

                $arr[] = realpath($file);
            }
        }
    }

    /**
     * @title 退出
     */
    public function logout() {

        cookie('admin', null);

        session('admin', null);

        $this->success('退出成功', url('admin/everyone/login'));
    }

    /**
     * @title 登录
     * @return type
     */
    public function login() {





        if (request()->isPost()) {

            //  后端验证
            $post = request()->post();
            foreach ($post as $key => $value) {
                $post[$key] = trim($value);
            }


            $msg = model('system_user')->login($post);
            if (empty($msg)) {
                // 
                $this->success('', url('admin/index/index'));
            } else {
                $this->error($msg);
            }
        } else {

            return view();
        }
    }

}
